package rgs.sphere.jdbc.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.math.BigInteger;
import java.util.Collection;

/**
 * @program: rgs-study0project
 * @description: 数据表精确查询分片策略
 * @author: Mr.Ren
 * @create: 2023-11-12 21:19
 **/
public class MyTablePreciseAlgorithm implements PreciseShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        //sql   select * from product where cid = xxx
        //分片键
        String cid = preciseShardingValue.getColumnName();
        //逻辑表名称（product）
        String logicTableName = preciseShardingValue.getLogicTableName();
        Long cidValue = preciseShardingValue.getValue();

        //实现 product_$->{1..2}即可
        BigInteger bigInteger = BigInteger.valueOf(cidValue);
        String suffix = bigInteger.mod(new BigInteger("2")).add(new BigInteger("1")).toString();
        String realTableName = logicTableName + "_" + suffix;
        if (collection.contains(realTableName)) {
            //最后返回物理表名称，就知道去哪里查了
            return realTableName;
        }

        throw new RuntimeException(realTableName+" table name is not exist");

    }
}
